package cn.ctyun.xstore

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener
import com.amazonaws.mobileconnectors.s3.transferutility.TransferState

class UploadObjectActivity : AppCompatActivity() {

    private val reqCode = 10010


    private lateinit var selectFileBtn: Button

    private lateinit var objectKeyText: EditText

    private lateinit var uploadProgressTextView: TextView


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_upload_object)
        objectKeyText = findViewById(R.id.object_key)
        selectFileBtn = findViewById(R.id.select_file_btn)
        uploadProgressTextView = findViewById(R.id.upload_progress_text)
        selectFileBtn.setOnClickListener {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type = "*/*"
            startActivityForResult(intent, reqCode)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode != reqCode) return
        if (resultCode != RESULT_OK) return
        data?.data?.let { uri ->
            val uploadKey = objectKeyText.text?.toString()
            if (uploadKey == null) {
                setProgressText(getString(R.string.object_hint))
                return
            }
            upload(uploadKey, contentResolver.openInputStream(uri), object : TransferListener {

                override fun onStateChanged(id: Int, state: TransferState?) {

                }


                override fun onProgressChanged(id: Int, bytesCurrent: Long, bytesTotal: Long) {
                    val progress = bytesCurrent.toFloat() / bytesTotal.toFloat() * 100
                    setProgressText("$progress%")
                }


                override fun onError(id: Int, ex: Exception?) {

                }
            })
        }

    }

    private fun setProgressText(text: String) {
        Handler(Looper.getMainLooper()).post {
            uploadProgressTextView.text = text
        }
    }
}